# arch/x86/Makefile
# x86架构启动代码构建规则

# 如果ARCH未定义，则设置默认值
ARCH ?= x86

# 源文件定义
BOOTSECT_SOURCE = bootsect.S
SETUP_SOURCE = setup.S

# 输出目录（相对于当前目录）
BUILD_DIR = ../../build/arch/$(ARCH)

# 中间文件
BOOTSECT_OBJECT = $(BUILD_DIR)/bootsect.o
SETUP_OBJECT = $(BUILD_DIR)/setup.o

# 最终输出文件
BOOTSECT_BIN = $(BUILD_DIR)/bootsect.bin
SETUP_BIN = $(BUILD_DIR)/setup.bin
BOOT_IMAGE = $(BUILD_DIR)/bootimage.bin

# 调试输出
BOOTSECT_LST = $(BUILD_DIR)/bootsect.lst
SETUP_LST = $(BUILD_DIR)/setup.lst

# 工具链
CC        = gcc
AS        = gcc
OBJCOPY   = objcopy
OBJDUMP   = objdump

# 编译选项
BOOTSECT_ASFLAGS = -m32 -fno-pie -no-pie -Wall

# 默认目标
.PHONY: all clean debug-build-dir

all: $(BOOT_IMAGE) boot-info

# 调试目标 - 显示BUILD_DIR路径
debug-build-dir:
	@echo "BUILD_DIR = $(BUILD_DIR)"
	@echo "Absolute path: $(abspath $(BUILD_DIR))"
	@echo "ARCH = $(ARCH)"

# 编译启动扇区
$(BOOTSECT_OBJECT): $(BOOTSECT_SOURCE)
	@echo "  AS      $(notdir $@)"
	@mkdir -p $(dir $@)
	@$(AS) -c $(BOOTSECT_ASFLAGS) $< -o $@

# 编译设置代码
$(SETUP_OBJECT): $(SETUP_SOURCE)
	@echo "  AS      $(notdir $@)"
	@mkdir -p $(dir $@)
	@$(AS) -c $(BOOTSECT_ASFLAGS) $< -o $@

# 生成二进制文件
$(BOOTSECT_BIN): $(BOOTSECT_OBJECT)
	@echo "  OBJCOPY $(notdir $@)"
	@$(OBJCOPY) -O binary $< $@

$(SETUP_BIN): $(SETUP_OBJECT)
	@echo "  OBJCOPY $(notdir $@)"
	@$(OBJCOPY) -O binary $< $@

# 生成反汇编列表
$(BOOTSECT_LST): $(BOOTSECT_OBJECT)
	@echo "  OBJDUMP $(notdir $@)"
	@$(OBJDUMP) -d $< > $@

$(SETUP_LST): $(SETUP_OBJECT)
	@echo "  OBJDUMP $(notdir $@)"
	@$(OBJDUMP) -d $< > $@

# 组合生成启动镜像
$(BOOT_IMAGE): $(BOOTSECT_BIN) $(SETUP_BIN)
	@echo "  BUILD   $(notdir $@)"
	@mkdir -p $(dir $@)
	@cat $(BOOTSECT_BIN) $(SETUP_BIN) > $@
	@echo "Boot image created: $(BOOT_IMAGE)"
	@ls -l $(BOOT_IMAGE)

# 显示构建信息
boot-info:
	@echo "Boot sector binary: $(BOOTSECT_BIN)"
	@echo "Setup binary: $(SETUP_BIN)"
	@echo "Combined boot image: $(BOOT_IMAGE)"

# 清理
clean:
	@echo "Cleaning x86 boot files..."
	-rm -rf $(BUILD_DIR)